#include "CServer.h"
#include "UserMgr.h"
CServer::CServer(boost::asio::io_context& ioc, short port):_ioc(ioc),_port(port),
_acceptor(_ioc,boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(),port))
{
	std::cout << "Chat Server start on port:" << _port << std::endl;
	StartAccept();
}

CServer::~CServer()
{
	std::cout << "~CServer" << std::endl;
}

void CServer::ClearSession(std::string session_id)
{
	if (_sessions.find(session_id) != _sessions.end())
	{
		UserMgr::GetInst().RmvUserSession(_sessions[session_id]->GetUserId());
	}
	{
		std::lock_guard<std::mutex> lock(_mtx);
		_sessions.erase(session_id);

	}

}

void CServer::HandleAccept(std::shared_ptr<CSession> session, const boost::system::error_code& ec)
{
	if (!ec)
	{
		session->Start();
		std::lock_guard<std::mutex> lock(_mtx);
		_sessions.emplace(std::make_pair(session->GetUuid(), session));
	}
	else
	{
		std::cerr << "HandleAccept err:" << ec.message() << std::endl;
	}
	StartAccept();
}

void CServer::StartAccept()
{
	auto& ioc = IOcontextPool::GetInst().GetIOC();
	std::shared_ptr<CSession> new_session = std::make_shared<CSession>(ioc, this);
	_acceptor.async_accept(new_session->GetSocket(), std::bind(&CServer::HandleAccept, this, new_session, std::placeholders::_1));
}
